import { useRoutes, useHref, useNavigate } from 'react-router-dom'
import { baseRoutes } from '@/router/index'
import { useEffect, useState } from 'react'
import { useSelectRouter } from '@/store/hooks'
import { cloneDeep } from 'lodash'

const useRoutesConfig = () => {
  window.progress.start()
  const href = useHref()
  const navigate = useNavigate()
  const [routes, setRoutes] = useState([...baseRoutes])
  const routess = useSelectRouter()

  useEffect(() => { // 初始化路由
    const getRoutes = (list) => {
      setRoutes(res => {
        res[0].children = [...list]
        return [...res]
      })
    }
    if (routess.length > 0) {
      getRoutes(cloneDeep(routess))
    }
  }, [routess])

  useEffect(() => { // 动态读取title
    const getParams = (list, path) => {
      for (const items of list) {
        if (path === items.path || path === items?.meta?.key) return items
        if (items.children && items.children.length > 0) {
          const res = getParams(items.children, path)
          if (res) return res
        }
      }
      return null
    }
    if (routes) {
      const res = getParams(routes, href)
      if (res) {
        const meta = res.meta
        document.title = meta?.title || ''
        if (href.startsWith('/conf')) {
          if (!meta.hasAuthIn) navigate('/nopermission')
        }
      }
    }
  }, [ navigate, routes, href])

  // progress
  useEffect(() => {
    window.progress.done()
    return () => {
      window.progress.start()
    }
  })
  return useRoutes(routes)
}
export default useRoutesConfig
